//
//  BoyeToken.m
//  bluebao
//
//  Created by boye_mac1 on 15/7/28.
//  Copyright (c) 2015年 Boye. All rights reserved.
//

#import "BoyeToken.h"
#import "BoyeHttpClient.h"

@implementation BoyeToken

+(NSString *)getAccessToken{
    return [[CacheFacade sharedCache] get:BOYE_ACCESS_TOKEN];
}
+(void )clearAccessToken{
    [[CacheFacade sharedCache] setObject:nil forKey:BOYE_ACCESS_TOKEN];
}
//是否存在有效token
+(NSString *)isTokenEffective{
    
    NSString * token = [[CacheFacade sharedCache] get:BOYE_ACCESS_TOKEN];

    if (token == nil) {
        [SVProgressHUD showWithStatus:@" token 失效!"];
        return nil;
    }
    
    return token;
}

//保存token 以及计算出过期的时间并保存

+(void)saveDataWithDic:(NSDictionary *)dic :(NSNumber *)questTime{
    NSString *access_token=[dic objectForKey:@"access_token"];
    double time=[[dic objectForKey:@"expires_in"] doubleValue];
    
    [[CacheFacade sharedCache] setObject:access_token forKey:BOYE_ACCESS_TOKEN afterTimeStamp:[NSNumber numberWithDouble:[questTime doubleValue] + time]];
    
}


//获取有效令牌
+(void)isTokenEffectiveComplete:(void(^)(NSString *  token))complete{
    
    NSString * boyeToken = [self isTokenEffective];
    
    if (boyeToken != nil) {
        complete (boyeToken);
        
    } else {
        [SVProgressHUD dismiss];
        //Token请求
        [self requestToken:^(NSString *reqToken) {
            if (reqToken) {
                complete(reqToken);
            }
        }];
    }
    
}

// TODO: zk 新的token请求方法
// token请求
+ (void)requestToken:(void (^)(NSString* reqToken))complete {
    
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    manager.responseSerializer = [AFJSONResponseSerializer serializerWithReadingOptions:NSJSONReadingMutableContainers];
    manager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"application/json", @"text/json", @"text/javascript",@"text/html", nil];

    // 请求token不用加密，参数固定为如下三个
    NSDictionary *params = @{@"grant_type":@"client_credentials",
                             @"client_id":BOYE_CLIENT_ID,
                             @"client_secret":BOYE_CLIENT_SECRET,};
    
//    [SVProgressHUD showWithStatus:@"请求Token..." maskType:SVProgressHUDMaskTypeClear];
    
    NSNumber *questTime = [NSDate currentTimeStamp];
    
    NSString *tokenUrl = [BOYE_API_URL stringByAppendingFormat:@"/token/index"];
    
    [manager POST:tokenUrl parameters:params success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSNumber *code = [responseObject valueForKey:@"code"];
        NSDictionary *tokenData = [responseObject valueForKey:@"data"];
        
        if ([code intValue] == 0){
            [self saveDataWithDic:tokenData :questTime];
            NSString *access_token = [tokenData objectForKey:@"access_token"];
//            [SVProgressHUD showSuccessWithStatus:@"Token请求成功"];
            complete(access_token);
        } else{
            [SVProgressHUD showErrorWithStatus:@"Token请求失败"];
        }

    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        [SVProgressHUD showErrorWithStatus:@"Token请求失败"];
    }];
    
}



@end
